package yxy.game.pm2.command.altar;

import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.debris;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.AltarMessage;
import yxy.game.pm2.message.PackageMessage;
import yxy.game.pm2.module.CurrencyHandle;

import java.util.Collection;

/** 祭坛 将魂献祭 */
@MessageType(proto = Command.AltarChip, classtype = AltarMessage.AltarChipRequest.class)
public class CMD_AltarChip extends Command<AltarMessage.AltarChipRequest> {

	@Override
	public void execute(MessageSource messageSource, AltarMessage.AltarChipRequest request) {
		String playerCode = messageSource.getTag();
		PackageMessage.Item item = request.getItem();

		AltarMessage.AltarChipResponse.Builder response = AltarMessage.AltarChipResponse.newBuilder();

		CurrencyType type = CurrencyType.forNumber(item.getType());
		if (type == null || !type.equals(CurrencyType.CT_碎片)) {
			send(messageSource, response, Result.ParamError);
			return;
		}
		debris data = DataCenter.getData(item.getDataId(), debris.class);
		if (data == null) {
			send(messageSource, response, Result.ParamError);
			return;
		}
		long num = Currency.number(playerCode, type, data.getId(),false);
		if (num < item.getNumber()) {
			send(messageSource, response, Result.AltarChipLack);//碎片数量不足
			return;
		}

		Collection<Currency> back = Currency.create(data.getDegenerationcost(), data.getDegenerationid(), data.getDegenerationnum());
		for (Currency bc : back) {
			bc.setNumber(bc.getNumber() * item.getNumber());
		}
		response.addAllBack(new CurrencyHandle().packItems(back));
		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, AltarMessage.AltarChipResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}